import React, { useState } from 'react';

const InteractiveGridLayer = ({ rows, columns, cellSize, gap, onLineDrawn }) => {
  const [isDrawing, setIsDrawing] = useState(false);
  const [startCell, setStartCell] = useState(null);
  const [hoverCell, setHoverCell] = useState(null);

  const calculateCenter = (row, col) => ({
    x: col * (cellSize + gap) + cellSize / 2,
    y: row * (cellSize + gap) + cellSize / 2,
  });

  const handleMouseDown = (row, col) => {
    setIsDrawing(true);
    setStartCell({ row, col });
  };

  const handleMouseEnter = (row, col) => {
    if (isDrawing) {
      setHoverCell({ row, col });
    }
  };

  const handleMouseUp = (row, col) => {
    if (isDrawing && startCell) {
      const endCell = { row, col };
      if (startCell.row !== endCell.row || startCell.col !== endCell.col) {
        onLineDrawn({ start: startCell, end: endCell, no: "", occupied: false });
      }
    }
    setIsDrawing(false);
    setStartCell(null);
    setHoverCell(null);
  };

  const gridRects = [];
  for (let row = 0; row < rows; row++) {
    for (let col = 0; col < columns; col++) {
      const x = col * (cellSize + gap);
      const y = row * (cellSize + gap);
      gridRects.push(
        <rect
          key={`${row}-${col}`}
          x={x}
          y={y}
          width={cellSize}
          height={cellSize}
          fill="transparent"
          stroke="transparent"
          onMouseDown={() => handleMouseDown(row, col)}
          onMouseEnter={() => handleMouseEnter(row, col)}
          onMouseUp={() => handleMouseUp(row, col)}
          style={{ cursor: 'pointer' }}
        />
      );
    }
  }

  return (
    <g pointerEvents="all">
      {gridRects}
      {isDrawing && hoverCell && startCell && (() => {
        const { x: x1, y: y1 } = calculateCenter(startCell.row, startCell.col);
        const { x: x2, y: y2 } = calculateCenter(hoverCell.row, hoverCell.col);
        return (
          <line
            x1={x1}
            y1={y1}
            x2={x2}
            y2={y2}
            stroke="blue"
            strokeWidth={4}
            strokeDasharray="6 4"
            pointerEvents="none"
          />
        );
      })()}
    </g>
  );
};

export default InteractiveGridLayer;
